import { defineStore } from 'pinia'

export type DumpType = 'framework' | 'operation' | 'debug'

interface WorkspaceDumpSelection {
  framework: string[]
  operation: string[]
  debug: string[]
}

function getDefaultSelection(): WorkspaceDumpSelection {
  return { framework: [], operation: [], debug: [] }
}

const STORAGE_KEY = 'logvision_dump_included_by_workspace_v1'

export const useDumpStore = defineStore('dumpStore', {
  state: () => ({
    includedByWorkspace: {} as Record<string, WorkspaceDumpSelection>,
    // 用于触发依赖刷新
    version: 0
  }),
  actions: {
    loadFromStorage(): void {
      try {
        const raw = localStorage.getItem(STORAGE_KEY)
        if (raw) {
          const parsed = JSON.parse(raw)
          this.includedByWorkspace = parsed || {}
        }
      } catch {
        // 忽略
      }
    },
    saveToStorage(): void {
      try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(this.includedByWorkspace))
      } catch {
        // 忽略
      }
    },
    ensureWorkspace(workspaceId: string): void {
      if (!workspaceId) return
      if (!this.includedByWorkspace[workspaceId]) {
        this.includedByWorkspace[workspaceId] = getDefaultSelection()
      }
    },
    isIncluded(workspaceId: string | undefined, type: DumpType, fileIdOrPath: string): boolean {
      if (!workspaceId) return false
      this.ensureWorkspace(workspaceId)
      const list = this.includedByWorkspace[workspaceId][type]
      return list.includes(fileIdOrPath)
    },
    setIncluded(workspaceId: string | undefined, type: DumpType, fileIdOrPath: string, included: boolean): void {
      if (!workspaceId) return
      this.ensureWorkspace(workspaceId)
      const list = new Set(this.includedByWorkspace[workspaceId][type])
      if (included) {
        list.add(fileIdOrPath)
      } else {
        list.delete(fileIdOrPath)
      }
      this.includedByWorkspace[workspaceId][type] = Array.from(list)
      this.version++
      this.saveToStorage()
    },
    clearWorkspace(workspaceId: string): void {
      if (!workspaceId) return
      delete this.includedByWorkspace[workspaceId]
      this.version++
      this.saveToStorage()
    },
    getIncludedPaths(workspaceId: string | undefined, type: DumpType): string[] {
      if (!workspaceId) return []
      this.ensureWorkspace(workspaceId)
      return this.includedByWorkspace[workspaceId][type]
    }
  }
})


